﻿using MediatR;
using Microsoft.AspNetCore.Components.Forms;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using System.Globalization;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Supplieries
{
    /// <summary>
    /// 导入供应商信息
    /// </summary>
    public class ImportSupplierHandler : IRequestHandler<ImportSupplierCommand, Result>
    {
        /// <summary>
        /// 所有国家仓储
        /// </summary>
        private readonly IBaseRepository<Countrys> _countryRepository;

        /// <summary>
        /// 城市仓储
        /// </summary>
        private readonly IBaseRepository<Citys> _cityRepository;

        /// <summary>
        /// 供应商分类仓储
        /// </summary>
        private readonly IBaseRepository<Classifications> _classificationsRepository;

        /// <summary>
        /// 供应商仓储
        /// </summary>
        private readonly IBaseRepository<Suppliers> _supplierRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ImportSupplierHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="countryRepository"></param>
        /// <param name="cityRepository"></param>
        /// <param name="classificationsRepository"></param>
        /// <param name="supplierRepository"></param>
        /// <param name="logger"></param>
        public ImportSupplierHandler(IBaseRepository<Countrys> countryRepository,
                                     IBaseRepository<Citys> cityRepository,
                                     IBaseRepository<Classifications> classificationsRepository,
                                     IBaseRepository<Suppliers> supplierRepository,
                                     ILogger<ImportSupplierHandler> logger)
        {
            _countryRepository = countryRepository;
            _cityRepository = cityRepository;
            _classificationsRepository = classificationsRepository;
            _supplierRepository = supplierRepository;
            _logger = logger;
        }

        /// <summary>
        /// 导入供应商信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(ImportSupplierCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                //获取文件扩展名 判断上传文件的类型是否正确
                var ext = Path.GetExtension(request.file.FileName);
                if (ext == ".xls" || ext == ".xlsx")
                {

                }
                else
                {
                    result.Msg = "您上传的文件类型不正确";
                    return result;
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    request.file.CopyTo(ms);
                    ms.Position = 0;

                    //根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls，XSSFWorkbook用于.xlsx)
                    IWorkbook wb = null;
                    if (ext == ".xls")//创建97-2003
                    {
                        wb = new HSSFWorkbook(ms);
                    }
                    else//创建2007及以上版本
                    {
                        wb = new XSSFWorkbook(ms);
                    }

                    //获取sheet 获取工作薄中的第一个工作表
                    ISheet sheet = wb.GetSheetAt(0);

                    int totalRows = sheet.LastRowNum;//总行数
                    int totalCells = sheet.GetRow(0).LastCellNum;//总列数

                    //创建一个用于从初解析后的数据的列表
                    var supplierList = new List<Suppliers>();

                    //循环总行数 开头必须是1 不然从表头开始添加
                    for (int i = 1; i <= totalRows; i++)
                    {
                        //获取当前行
                        IRow row = sheet.GetRow(i);

                        //这个类必须写到循环里边 不然只能添加一行
                        var dto = new Suppliers();//在循环内创建新的实例

                        //下标从0开始 导入时 外键需进行判断
                        dto.SupplierCoding = row.GetCell(0).ToString();
                        dto.SupplierName = row.GetCell(1).ToString();
                        dto.SupplierDiff = row.GetCell(2).ToString();
                        dto.SupplierPhone = row.GetCell(3).ToString();
                        dto.SupplierAddress = row.GetCell(4).ToString();
                        //获取国家
                        var countryName = row.GetCell(5).ToString();
                        var country = await (await _countryRepository.GetAll()).Where(c => c.CountryName == countryName).FirstAsync();
                        //将查到的数据 id值传给外键
                        dto.CountryId = country.CountryId;

                        //获取城市
                        var cityName = row.GetCell(6).ToString();
                        var city = await (await _cityRepository.GetAll()).Where(c => c.CityName == cityName).FirstAsync();
                        //将查到的数据 id值传给外键
                        dto.CityId = city.CityId;

                        //获取供应商分类
                        var classificationName = row.GetCell(7).ToString();
                        var supplierClassification = await (await _classificationsRepository.GetAll()).Where(c => c.ClassIficationsName == classificationName).FirstAsync();
                        //将查到的数据 id值传给外键
                        dto.ClassificationId = supplierClassification.ClassIficationsId;
                        dto.SupplierLabel = row.GetCell(8).ToString();
                        dto.CompanyLogo = row.GetCell(9).ToString() == "是" ? 1 : 2;
                        dto.Identification = row.GetCell(10).ToString() == "是" ? 1 : 2;
                        dto.SupplierStatus = row.GetCell(11).ToString() == "有效" ? 1 : 2;
                        //是否删除默认赋值 未删除
                        dto.IsSupplier = 1;
                        dto.CreatedOwner = row.GetCell(12).ToString();
                        //创建日期转换
                        //日期在excel表中必须是年月日格式 但不能加时分秒 (注意!!!!)
                        string inputDate = row.GetCell(13).ToString();
                        string[] multipleFormats = { "dd-M月-yyyy", "yyyy-M-dd" };
                        DateTime parsedDate;
                        foreach (var format in multipleFormats)
                        {
                            if (DateTime.TryParseExact(inputDate, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
                            {
                                dto.CreatedTime = Convert.ToDateTime(parsedDate.ToString("yyyy-MM-dd"));
                                break;//成功解析后跳出循环
                            }
                        }

                        //将数据添加到数据集合中
                        supplierList.Add(dto);
                    }
                    //跳出循环后 使用AddRange进行批量添加
                    var res = _supplierRepository.AddRange(supplierList);

                    //判断是否添加成功
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "导入供应商成功";
                    }
                    else
                    {
                        result.Msg = "导入供应商失败";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Msg = "导入供应商异常" + ex.Message;
                _logger.LogError("导入供应商异常" + ex.Message);
            }
            return result;
        }
    }
}
